package com.e3.web.login.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.e3.core.base.Session;
import com.e3.web.core.server.HttpSessionHelper;
/**
 * 登录系统的入口。
 * @author Janty
 *
 */
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = -3671443844814583171L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//检查校验码是否正确生成
		if(!checkValidateCode(request, response)){
			gotoLoginJSP(request, response);
			return;
		}
		
		LoginForm loginForm = getLoginForm(request);
		//值校验
		if(!checkInputValues(request, response, loginForm)){
			gotoLoginJSP(request, response);
			return;
		}
		
		//重复登陆
		if(hasLogin(request, response, loginForm)){
			gotoLoginJSP(request, response);;
			return;
		}
		
		//校验密码
		if(!isValidUser(request, response, loginForm)){
			gotoLoginJSP(request, response);
			return;
		}
				
		//进入系统
		login(request, response,loginForm);
	}
	
	private void gotoLoginJSP(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		LoginHelper.gotoLogin(request, response);
	}

	private boolean checkValidateCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String code = (String) HttpSessionHelper.getAttribute(request,ValidateCodeServlet.VALIDATE_CODE);
		if (code == null) {
			return false;
		}
		return true;
	}
	
	private boolean checkInputValues(HttpServletRequest request, HttpServletResponse response,LoginForm loginForm) throws ServletException, IOException{
		StringBuffer msg = new StringBuffer();
		String code = (String) HttpSessionHelper.getAttribute(request,ValidateCodeServlet.VALIDATE_CODE);
		String corpCode = loginForm.getCorpCode();
		String userCode = loginForm.getUserCode();
		String password = loginForm.getPassword();
		String validateCode = loginForm.getValidateCode();
		
		List<String> msgs = new ArrayList<String>();
		if(corpCode == null || corpCode.trim().length()==0){
			msgs.add("公司代码");
		}
		if(userCode == null || userCode.trim().length()==0){
			msgs.add("用户代码");
		}
		if(password == null || password.trim().length()==0){
			msgs.add("用户密码");
		}
		if(validateCode == null || validateCode.trim().length()==0){
			msgs.add("校验码");
		}
		
		int size = msgs.size();
		if(size>0){
			msg.append("请输入");
			for (int i=0;i<size;i++) {
				String ms = msgs.get(i);
				if(i < size-1){
					msg.append(ms+",");
				}
				else{
					msg.append(ms);
				}
			}
			loginForm.setErrMessage(msg.toString());
			return false;
		}
		
		if(!code.equalsIgnoreCase(validateCode)){
			loginForm.setErrMessage("校验码不正确，请重新输入");
			return false;
		}
		//成功后构造Session对象并放入当前会话中
		Session session = LoginHelper.getSession(request);
		session.setCorpCode(corpCode);
		session.setUserCode(userCode);
		session.setLoginTime(new Date());
		session.setLoginAddress(request.getRemoteAddr());
		
		return true;
	}
	
	private boolean hasLogin(HttpServletRequest request, HttpServletResponse response,LoginForm loginForm) throws ServletException, IOException{
		if(LoginHelper.isLogined(request)){
			loginForm.setErrMessage("该用户已经在其他地方登录。");
			return true;
		}
		return false;
	}
	
	private boolean isValidUser(HttpServletRequest request, HttpServletResponse response,LoginForm loginForm) throws ServletException, IOException{
		return true;
	}
	
	private void login(HttpServletRequest request, HttpServletResponse response,LoginForm loginForm) throws ServletException, IOException{
		try {
			LoginHelper.login(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			loginForm.setErrMessage("登录失败，请联系管理员。");
			LoginHelper.gotoLogin(request, response);
		} 
	}
	
	private LoginForm getLoginForm(HttpServletRequest request) {
		LoginForm loginForm = (LoginForm) request.getAttribute("loginForm");
		if(loginForm == null){
			loginForm = new LoginForm();
			request.setAttribute("loginForm", loginForm);
		}
		String corpCode = request.getParameter("corpCode");
		String userCode = request.getParameter("userCode");
		String password = request.getParameter("password");
		String validateCode = request.getParameter("validateCode");
		
		loginForm.setCorpCode(corpCode);
		loginForm.setUserCode(userCode);
		loginForm.setPassword(password);
		loginForm.setValidateCode(validateCode);
		return loginForm;
	}
}
